package com.sdyd.antivirus.utils;

import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

/**
 * @author liujia
 * @date 2020/2/2 19:43
 **/
public class FileUtils {
    /**
     * 下载excel：根据从数据库提取数据组装好的workbook，输出文件流，实现下载文件
     */
    public static void downloadFile(Workbook workbook, HttpServletResponse response) {
        try {
            //设置response的内容类型
            response.setContentType("application/octet-stream");

            // 设置下载文件的名字
            String fileName = UUID.randomUUID().toString()+".xlsx";
            fileName = java.net.URLEncoder.encode(fileName,"utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);

            //获取response的输出流，转化为高效缓冲输出流
            OutputStream fos = new BufferedOutputStream(response.getOutputStream());

            //输出
            workbook.write(fos);
            fos.flush();
            fos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
